package net.hn.hnms.biz.mine.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.hn.hnms.biz.api.mine.model.AlarmMessageItemVo;
import net.hn.hnms.biz.mine.domain.AlarmConfiguration;
import net.hn.hnms.biz.mine.domain.AlarmConfigurationKey;
import net.hn.hnms.biz.mine.domain.AlarmMessageLog;
import net.hn.hnms.biz.mine.repository.AlarmConfigurationRepository;
import net.hn.hnms.biz.mine.repository.AlarmMessageLogRepository;
import net.hn.hnms.biz.mine.service.MessageService;
import net.hn.hnms.sys.common.core.domain.R;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.system.api.RemoteDeptService;
import net.hn.hnms.sys.system.api.RemoteUserService;
import net.hn.hnms.sys.system.api.domain.SysDept;
import net.hn.hnms.sys.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 智呈物联 pan'sx
 * 2022/11/14 15:36
 * 1.0 version
 */
@RestController
@RequestMapping("alarmNotifyConfig")
@Api(value = "报警推送消息控制器", tags = {"报警推送消息配置"})
public class AlarmConfigurationController {
    @Autowired
    private AlarmConfigurationRepository alarmConfigurationRepository;
    @Autowired
    private RemoteDeptService remoteDeptService;
    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private AlarmMessageLogRepository alarmMessageLogRepository;

    public static String[] alarmType = {"安全监控", "人员定位", "火灾", "水害", "顶板", "地压", "粉尘",
            "综掘", "供电", "通风","压风", "提升", "辅运","协同开采","综采", "煤流","给排水", "瓦斯抽放"};

    @GetMapping("getAlarmType")
    @ApiOperation("获取报警类型")
    public R<List<String>> getAlarmType() {
        return R.ok(Arrays.asList(alarmType));
    }

    @PostMapping("addOrUpdate")
    @ApiOperation("添加或修改")
    public R<AlarmConfiguration> addOrUpdate(@RequestBody @Validated AlarmConfiguration alarmConfiguration) {
        if (!Arrays.asList(alarmType).contains(alarmConfiguration.getKey().getAlarmType())) return R.fail("未知的报警类型");
        AlarmConfiguration save = alarmConfigurationRepository.save(alarmConfiguration);
        return R.ok(save);
    }

    @GetMapping("listData")
    @ApiOperation("配置列表")
    public R<List<AlarmConfiguration>> getList() {
        List<AlarmConfiguration> all = alarmConfigurationRepository.findAll();
        List<Long> deps = new ArrayList<>();
        List<Long> users = new ArrayList<>();
        for (AlarmConfiguration configuration : all) {
            if (StringUtils.isNotBlank(configuration.getDepIds())) {
                String[] depss = configuration.getDepIds().split(",");
                for (String depid : depss) {
                    deps.add(Long.parseLong(depid));
                }

            }
            if (StringUtils.isNotBlank(configuration.getUserIds())) {
                String[] split = configuration.getUserIds().split(",");
                for (String userId : split) {
                    users.add(Long.parseLong(userId));
                }
            }
        }
        List<SysDept> deptByIds = new ArrayList<>();
        if (!deps.isEmpty()) {
            deptByIds = remoteDeptService.getDeptByIds(deps);
        }

        Map<Long, String> depMap = deptByIds.stream().collect(Collectors.toMap(s -> s.getDeptId(), s -> s.getDeptName(), (key1, key2) -> key1));

        List<LoginUser> userListByIdList = new ArrayList<>();
        if (!users.isEmpty()) {
            userListByIdList = remoteUserService.getUserListByIdList(users);
        }
        Map<Long, String> userMap = userListByIdList.stream().collect(Collectors.toMap(s -> s.getUserId(), s -> s.getNickname(), (key1, key2) -> key1));
        for (AlarmConfiguration configuration : all) {
            List<String> depName = new ArrayList<>();

            if (StringUtils.isNotBlank(configuration.getDepIds())) {
                String[] depss = configuration.getDepIds().split(",");
                for (String depid : depss) {
                    if (depMap.get(Long.parseLong(depid)) != null) {
                        depName.add(depMap.get(Long.parseLong(depid)));
                    }
                }

            }
            configuration.setDepName(StringUtils.join(depName, ","));
            List<String> userName = new ArrayList<>();
            if (StringUtils.isNotBlank(configuration.getUserIds())) {
                String[] split = configuration.getUserIds().split(",");
                for (String userId : split) {
                    if (userMap.get(Long.parseLong(userId)) != null) {
                        userName.add(userMap.get(Long.parseLong(userId)));
                    }
                }
            }
            configuration.setUserNames(StringUtils.join(userName, ","));
        }
        return R.ok(all);
    }

    @PostMapping("sendMessage")
    @ApiOperation("发送报警消息")
    public R sendMessage(@RequestBody @Validated AlarmMessageLog log) {
        if (!Arrays.asList(alarmType).contains(log.getAlarmType())) return R.fail("未知的报警类型");
        AlarmConfigurationKey key=new AlarmConfigurationKey();
        key.setAlarmLevel(log.getAlarmLevel());
        key.setAlarmType(log.getAlarmType());
        key.setSensorType(log.getSensorType());
        Optional<AlarmConfiguration> byId = alarmConfigurationRepository.findById(key);
        if (!byId.isPresent()) {
            return R.fail("未知的报警类型");
        }
        if (StringUtils.isBlank(log.getArea())) {
            return R.fail("报警内容不可为空");
        }
        AlarmConfiguration configuration = byId.get();
        Set<String> toUsers = new HashSet<>();
        if (StringUtils.isNotBlank(configuration.getDepIds())) {
            String[] deptIds = configuration.getDepIds().split(",");
            List deptIdList = new ArrayList();
            for (String id : deptIds) {
                deptIdList.add(Long.parseLong(id));
            }
            toUsers.addAll(remoteUserService.getUserListByDept(deptIdList));
        }
        if (StringUtils.isNotBlank(configuration.getUserIds())) {
            String[] userIds = configuration.getUserIds().split(",");
            List users = new ArrayList();
            for (String id : userIds) {
                users.add(Long.parseLong(id));
            }

            List<LoginUser> userListByIdList = remoteUserService.getUserListByIdList(users);
            List<String> collect = userListByIdList.stream().map(LoginUser::getUsername).collect(Collectors.toList());
            toUsers.addAll(collect);
        }
        if (toUsers.isEmpty()) {
            return R.fail("未配置有效的接收对象。");
        }
        log.setToUsers(StringUtils.join(toUsers, "|"));
        if(log.getTime()==null){log.setTime(new Date());}
        JSONObject jsonObject = messageService.alarmMessage(log);
        alarmMessageLogRepository.save(log);
        return R.ok(jsonObject);
    }


    @GetMapping("alarmMessageItem")
    @ApiOperation("安全监控报警消息")
    public R<List<AlarmMessageItemVo>> alarmMessageItem(@ApiParam("报警系统") String alarmType){
        return R.ok(messageService.alarmMessageItem(alarmType));
    }
}
